package com.bnzj.cloud.gateway.controller;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.bnzj.cloud.gateway.properties.AuthServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;

import com.bnzj.cloud.gateway.external.CustomTokenParseHandler;
import com.bnzj.core.util.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ExternalTokenController
 * @Description 外部第三方token处理controller
 * @Author
 * @Date 2020/3/24
 * @Version V1.0
 **/
@Slf4j
@Controller
@RequestMapping("/external/api")
public class ExternalTokenController {

    @Autowired
    private AuthServerProperties authServerProperties;

    @Autowired
    private CustomTokenParseHandler customTokenParseHandler;
    
    /*@Autowired
    private StringRedisTemplate stringRedisTemplate;*/

    @Autowired
    private RestTemplate restTemplate;

    private static final String HEAD_EXTERNAL_KEY = "E-KEY";
    private static final String HEAD_EXTERNAL_VALUE = "E-VALUE";

    @GetMapping("/token")
    public String getTokenByExternalTicket(ServerWebExchange swe, String ticket, String redirectUri) throws Exception{
        String token = null;
        try {
            String username = customTokenParseHandler.getUserNameByToken(ticket);
            if(username != null) {
                String url = new StringBuilder(authServerProperties.getServerDomain())
                        .append(authServerProperties.getTokenPath())
                        .append("?").append("client_id={clientId}")
                        .append("&client_secret={clientSecret}")
                        .append("&grant_type={grantType}")
                        .append("&username={username}")
                        .append("&password={password}").toString();
                Map<String, String> requestParams = new HashMap<>();
                requestParams.put("clientId", authServerProperties.getClientId());
                requestParams.put("clientSecret", authServerProperties.getClientSecret());
                requestParams.put("grantType", authServerProperties.getGrantType());
                requestParams.put("username", username);
                requestParams.put("password", username);

                HttpHeaders headers = new HttpHeaders();
                String eKey = UUID.randomUUID().toString();
                String eValue = UUID.randomUUID().toString();
                headers.set(HEAD_EXTERNAL_KEY, eKey);
                headers.set(HEAD_EXTERNAL_VALUE, eValue);
                //stringRedisTemplate.opsForValue().set(eKey, eValue, Duration.ofSeconds(60));
                HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(null, headers);
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
                requestFactory.setConnectTimeout(10000);
                requestFactory.setReadTimeout(10000);
                //restTemplate.setRequestFactory(requestFactory);
                //ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, request, String.class, requestParams);
                String resultStr = "";
                JsonNode node = JsonUtils.valueToTree(resultStr);
                if(node.findPath("access_token") != null){
                    token = node.findPath("access_token").asText();
                }
            }
        }catch (Exception e){
            log.error("", e);
        }
        swe.getResponse();
        String fullRedirectUri = redirectUri+"?token="+token;
        return "redirect:" + fullRedirectUri;
    }

}
